﻿using AutoMapper;
using Inventory.API.Application.Command.WarehouseManagementCommand;
using Inventory.Errorcode;
using Inventory.Errorcode.ErrorCode;
using Inventory.Infrastructure.Interfaces;
using MediatR;

namespace Inventory.API.Application.CommandHandler.WarehouseManagementCommandHandler
{
    public class UpdateWarehousingCommandHanlder : IRequestHandler<UpdateWarehousingCommand, ApiResult>
    {
        private readonly ILogger<UpdateWarehousingCommandHanlder> _logger;
        private readonly IWarehousemanagementRepository repository;
        private readonly IMapper mapper;

        public UpdateWarehousingCommandHanlder(ILogger<UpdateWarehousingCommandHanlder> logger, IWarehousemanagementRepository repository, IMapper mapper)
        {
            _logger = logger;
            this.repository = repository;
            this.mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpdateWarehousingCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var warehousing = await repository.GetAsync(x => x.Warehousemanagementid == request.Warehousemanagementid);
                if (warehousing == null)
                {
                    return ApiResult.Fail("仓库不存在", StatusCodeEnum.NotFound);
                }
                else
                {
                    var updatewarehousing = mapper.Map(request, warehousing);
                    await repository.UpdateAsync(updatewarehousing);
                    return ApiResult.Success(StatusCodeEnum.Success);
                }


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error occured while updating warehousing");
                throw;
            }
        }
    }
}
